#include <iostream>
#include <unistd.h>
#include <cstring>
using namespace std;

int main()
{
    int result = -1;
    int fd[2],nbytes;
    pid_t pid;
    char string[] = {"hello world "};
    char readbuffer[80];
    int *write_fd = &fd[1];
    int *read_fd = &fd[0];
    result = pipe(fd);//创建管道
    if(-1 == result)
    {
        cout<<"创建管道失败!"<<endl;
        return -1;
    }
    pid = fork();
    if(-1 == pid)
    {
        cout<<"fork 进程失败\n";
        return -1;
    }
    else if(0 == pid)
    {
        //关闭读端，写入数据到管道
        close(*read_fd);
        result = write(*write_fd,string,strlen(string));
        return 0;
    }
    else
    {
        //关闭写端，从管道读取数据
        close(*write_fd);
        nbytes = read(*read_fd,readbuffer,sizeof(readbuffer));
        cout<<"接收到数据长度:"<<nbytes<<" 数据"<<readbuffer<<endl;
    }
    return 0;
}
